package Communication;

/**
 * 线程通信的应用
 * 生产者/消费者的问题
 */
class Clerk{
    private int productCont=0;
    //生产产品
    public synchronized void producerProduct() {
       if (productCont<20){
           productCont++;
           System.out.println(Thread.currentThread().getName()+":开始生产第"+ productCont+"个产品");
           notify();
       }else {
           //等待
           try {
               wait();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
    }
    //消费产
    public synchronized void consumerProduct() {
        if (productCont>0){

            System.out.println(Thread.currentThread().getName()+":开始消费第"+ productCont+"个产品");
            productCont--;
            notify();
        }else {
            //等待
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}
class Producer extends Thread{
    private static Clerk clerk;

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run(){
        System.out.println(getName()+":"+"开始生产产品");
        while (true){
            clerk.producerProduct();
        }
    }

}

class Consumer extends Thread{
    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }
    @Override
    public void run(){
        System.out.println(getName()+":"+"开始消费产品");
        while (true){
            clerk.consumerProduct();
        }
    }

}

public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Producer p1 = new Producer(clerk);


        Consumer c1 = new Consumer(clerk);
        p1.setName("生产者1");
        c1.setName("消费者1");
        p1.start();


        c1.start();

    }

}
